package com.transactional.service.innerclass;

import com.transactional.bean.User;
import com.transactional.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Deacription 事物在同一个方法中的表现形式
 * @Author baohuajie
 * @Date 2021/5/12 9:55
 * @Version 1.0
 **/
@Service
public class InnerService1 {

    @Autowired
    private UserDao userDao;

    /**
     * 外层有@Transactional，内层没@Transactional：外层和外层在同一个事物中
     * @param user
     * @return
     */
    @Transactional
    public int demo1(User user){
        user.setUserName(user.getUserName() + " InnerService1.demo1");
        int i = userDao.insert(user);
        int i1 = demo2(user);
        return i + i1;
    }

    public int demo2(User user){
        user.setUserName(user.getUserName() + " InnerService1.demo2");
        int i = userDao.insert(user);
        try {
            int a = 1/0;
        } catch (Exception e) {

            throw new RuntimeException();
        }
        return i;
    }


    /**
     * 外层没有@Transactional，内层有@Transactional：内层、外层的事物不起作用。但是在外部类调用demo4时起作用，demo4的事物起作用
     * @param user
     * @return
     */
    public int demo3(User user){
        user.setUserName(user.getUserName() + " InnerService1.demo1");
        int i = userDao.insert(user);
        int i1 = demo4(user);
        return i + i1;
    }

    @Transactional
    public int demo4(User user){
        user.setUserName(user.getUserName() + " InnerService1.demo2");
        int i = userDao.insert(user);
        try {
            int a = 1/0;
        } catch (Exception e) {
            throw new RuntimeException();
        }
        return i;
    }

}
